package com.bbcloud.service.impl;

import com.bbcloud.common.ServerResponse;
import com.bbcloud.common.TokenCache;
import com.bbcloud.dao.DeviceMapper;
import com.bbcloud.dao.UserMapper;
import com.bbcloud.pojo.Device;
import com.bbcloud.pojo.User;
import com.bbcloud.service.IDeviceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by liuzhu on 2018/12/27.
 */
@Service("iDeviceService")
public class DeviceServiceImpl implements IDeviceService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    public ServerResponse<Device> selectDeviceWithDeviceId(String token, String userId, String deviceId){
        User user = userMapper.selectUser(userId);
        if (user == null){
            return ServerResponse.createByErrorMessage("The user doesn't exist.");
        }
        String tokenValid = TokenCache.getKey(TokenCache.TOKEN_PREFIX+user.getEmail());
        if (!StringUtils.equals(tokenValid,token)){
            return ServerResponse.createByErrorMessage("Please log in again");
        }
        Device device = deviceMapper.selectByinvitationCode(deviceId);
        if (device == null){
            return ServerResponse.createByErrorMessage("No device info");
        }
        return ServerResponse.createBySuccess(device);
    }
}
